package com.newway.wechat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newway.common.Result;
import com.newway.wechat.context.UserInfoContext;
import com.newway.wechat.dto.MaterialInfoRequestDto;
import com.newway.wechat.dto.MaterialRecordDto;
import com.newway.wechat.entity.MaterialInfo;
import com.newway.wechat.entity.MaterialRecord;
import com.newway.wechat.mapper.MaterialInfoMapper;
import com.newway.wechat.mapper.MaterialRecordMapper;
import com.newway.wechat.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wechat")
public class MaterialInfoController {

    @Autowired
    MaterialInfoMapper materialInfoMapper;

    @Autowired
    MaterialRecordMapper materialRecordMapper;

    @Autowired
    ExcelService excelService;

    /**
     * 材料新增
     * @param materialInfo
     * @return
     */
    @PostMapping("/materialInfo/save")
    public Result saveMaterialInfo(@RequestBody MaterialInfo materialInfo){
        MaterialInfo db = materialInfoMapper.selectById(materialInfo.getMaterialId());
        if(db!=null){
            return Result.fail("当前"+db.getMaterialId()+"数据已存在，不可重复添加");
        }
        //主表信息填充
        Date date = new Date();
        materialInfo.setCreateTime(date);
        materialInfo.setInputUser(UserInfoContext.getUserInfo().getId());
        materialInfo.setOutgoingQuantity(0);
        materialInfo.setBalanceQuantity(materialInfo.getIncomeQuantity());
        //记录信息填充
        MaterialRecord materialRecord = new MaterialRecord();
        materialRecord.setMaterialId(materialInfo.getMaterialId());
        materialRecord.setOperator(UserInfoContext.getUserInfo().getId());
        materialRecord.setOperatorName(UserInfoContext.getUserInfo().getNickName());
        materialRecord.setIncomeQuantity(materialInfo.getIncomeQuantity());
        materialRecord.setBalanceQuantity(materialInfo.getIncomeQuantity());
        materialRecord.setOutgoingQuantity(0);
        materialRecord.setCreateTime(date);
        materialRecord.setOperationType("1");
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = today.format(formatter);
        materialRecord.setOperationTime(formattedDate);
        materialRecord.setRemark(materialInfo.getSummary());
        materialInfoMapper.insert(materialInfo);
        materialRecordMapper.insert(materialRecord);
        return Result.success(0);
    }


    @PostMapping("/materialInfo/list")
    public Result<List> listMaterialInfo(@RequestBody MaterialInfoRequestDto requestDto){
        QueryWrapper queryWrapper = new QueryWrapper<MaterialInfo>();
        if(requestDto.getKeyWords()!=null && !"".equals(requestDto.getKeyWords())){
            queryWrapper.like("material_id",requestDto.getKeyWords());
            queryWrapper.or();
            queryWrapper.like("material_name",requestDto.getKeyWords());
        }
        List<MaterialInfo> list = materialInfoMapper.selectList(queryWrapper);
        return Result.success(list);
    }

    /**
     * 出入库
     * @param materialRecordDto
     * @return
     */
    @PostMapping("/materialRecord/save")
    public Result materialRecordSave(@RequestBody MaterialRecordDto materialRecordDto){
        MaterialInfo materialInfo = materialInfoMapper.selectById(materialRecordDto.getId());
        if(materialInfo==null){
            return Result.fail("当前数据不存在，请刷新重试");
        }
        Date date = new Date();
        MaterialRecord materialRecord = new MaterialRecord();
        materialRecord.setMaterialId(materialRecordDto.getId());
        materialRecord.setOperator(UserInfoContext.getUserInfo().getId());
        materialRecord.setOperationType(materialRecordDto.getType());
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = today.format(formatter);
        materialRecord.setOperationTime(formattedDate);
        materialRecord.setCreateTime(date);
        materialRecord.setOperatorName(UserInfoContext.getUserInfo().getNickName());
        //入库
        if("1".equals(materialRecordDto.getType())){
            int in = materialInfo.getIncomeQuantity() + materialRecordDto.getCount();
            int total = materialInfo.getBalanceQuantity() + materialRecordDto.getCount();
            materialInfo.setIncomeQuantity(in);
            materialInfo.setBalanceQuantity(total);
            materialRecord.setIncomeQuantity(materialRecordDto.getCount());
            materialRecord.setBalanceQuantity(total);
        }else{
            //出库
            if(materialInfo.getBalanceQuantity()<materialRecordDto.getCount()){
                return Result.fail("出库失败:出库数量大于当前结存数量");
            }
            int balance = materialInfo.getBalanceQuantity() - materialRecordDto.getCount();
            int out = materialInfo.getOutgoingQuantity() + materialRecordDto.getCount();
            materialInfo.setOutgoingQuantity(out);
            materialInfo.setBalanceQuantity(balance);
            materialRecord.setOutgoingQuantity(out);
            materialRecord.setBalanceQuantity(balance);
        }
        materialInfoMapper.updateById(materialInfo);
        materialRecordMapper.insert(materialRecord);
        return Result.success(0);
    }


    /**
     * 模板下载
     * @return
     * @throws IOException
     */
    @GetMapping("/download/materialRecord")
    public ResponseEntity<?> downloadPdf(String id) throws IOException {
        return excelService.downloadExcelTemplate(id);
        /*Resource resource = new ClassPathResource("templates/records."+downloadDto.getType());
        if (!resource.exists()) {
            throw new IOException("PDF file not found");
        }
        String filename = URLEncoder.encode("records."+downloadDto.getType(), StandardCharsets.UTF_8.name());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", filename);
        try {
            return ResponseEntity.ok()
                    .contentType("pdf".equals(downloadDto.getType())?MediaType.APPLICATION_PDF:MediaType.APPLICATION_OCTET_STREAM)
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            throw new IOException("文件下载异常");
        }*/
    }


    /**
     * 物料删除
     * @param id
     * @return
     */
    @PostMapping("/materialInfo/del/{id}")
    public Result materialDel(@PathVariable("id") String id){
        int delete = materialInfoMapper.deleteById(id);
        return Result.success(delete);
    }

}
